<template>
    <f7-page @page:beforein="pageBeforeIn">
        <f7-navbar>
            <f7-nav-left>
                <f7-link @click="$f7router.back()">
                    <f7-icon icon="icon-back" style="margin-left:15px;"></f7-icon>
                </f7-link>
            </f7-nav-left>
            <f7-nav-title title="房间详情"></f7-nav-title>
            <f7-subnavbar>
                <f7-toolbar tabbar>
                    <f7-link v-show="hasPermissionContractor" tab-link="#contractor" 
                        :tab-link-active="hasPermissionContractor && !hasPermissionSupervisor && !hasPermissionConstructor">
                        <span class="tabbar-label">施工</span>
                    </f7-link>
                    <f7-link v-show="hasPermissionSupervisor" tab-link="#supervisor" 
                        :tab-link-active="hasPermissionSupervisor && !hasPermissionConstructor">
                        <span class="tabbar-label">监理</span>
                    </f7-link>
                    <f7-link v-show="hasPermissionConstructor" tab-link="#constructor" 
                        :tab-link-active="hasPermissionConstructor">
                        <span class="tabbar-label">建设</span>
                    </f7-link>
                </f7-toolbar>
            </f7-subnavbar>
        </f7-navbar>
        <f7-block strong style="margin-top:0; margin-bottom:0; padding-top:3px; padding-bottom:3px;">
            <f7-block-title style="margin-top:5px;">
                <f7-row style="color:#007aff;">
                    <f7-col width="50" @click="placeCascaderOpen">
                        <p style="font-size:14px !important; margin-top:0; margin-bottom:0;">
                            {{(buildingId && $store.state.global.buildingMap[buildingId].building_name) + ' - ' + 
                            (unitId && $store.state.global.unitMap[unitId].unit_name + '单元')}}
                        </p>
                        <p style="font-size:14px !important; margin-top:0; margin-bottom:0;">
                            {{floorId && ($store.state.global.floorMap[floorId].floor_name + '层') + 
                            (houseId == null ? '' : ('-' + $store.state.global.houseMap[houseId].house_name))}}
                        </p>
                    </f7-col>
                    <f7-col width="50" @click="checkItemCascaderOpen">
                        <p style="font-size:14px !important; margin-top:0; margin-bottom:0;">
                            {{parentProblemClassId && $store.state.global.problemClassMap[parentProblemClassId].problem_class_name}}
                        </p>
                        <p style="font-size:14px !important; margin-top:0; margin-bottom:0;">
                            {{problemClassId && $store.state.global.problemClassMap[problemClassId].problem_class_name}}
                        </p>
                    </f7-col>
                </f7-row>
            </f7-block-title>
        </f7-block>
        <f7-tabs>
            <f7-tab id="contractor" :tab-active="hasPermissionContractor && !hasPermissionSupervisor && !hasPermissionConstructor">
                <WorkbenchQualityMeasureProblemDetail :problem="qualityMeasure['施工单位' ] " 
                	@updateProblem="updateProblem"
                    v-if="qualityMeasure['施工单位' ] != null">
                </WorkbenchQualityMeasureProblemDetail>
                <WorkbenchQualityMeasureProblemRegist :houseId="houseId" 
                    :itemId="itemId" :unitId="unitId" :floorId="floorId"
                    appPermission="施工单位"
                    @submitedProblem="submitedProblem"
                    v-else-if="hasPermissionContractor && !hasPermissionSupervisor && !hasPermissionConstructor">
                </WorkbenchQualityMeasureProblemRegist>
            </f7-tab>
            <f7-tab id="supervisor" :tab-active="hasPermissionSupervisor && !hasPermissionConstructor">
                <WorkbenchQualityMeasureProblemDetail :problem="qualityMeasure['监理单位' ] " 
                	@updateProblem="updateProblem"
                    v-if="qualityMeasure['监理单位' ] != null">
                </WorkbenchQualityMeasureProblemDetail>
                <WorkbenchQualityMeasureProblemRegist :houseId="houseId" 
                    :itemId="itemId" :unitId="unitId" :floorId="floorId"
                    appPermission="监理单位"
                    @submitedProblem="submitedProblem"
                    v-else-if="hasPermissionSupervisor && !hasPermissionConstructor">
                </WorkbenchQualityMeasureProblemRegist>
            </f7-tab>
            <f7-tab id="constructor" :tab-active="hasPermissionConstructor">
                <WorkbenchQualityMeasureProblemDetail :problem="qualityMeasure['建设单位' ] " 
                	@updateProblem="updateProblem"
                    v-if="qualityMeasure['建设单位' ] != null">
                </WorkbenchQualityMeasureProblemDetail>
                <WorkbenchQualityMeasureProblemRegist :houseId="houseId" 
                    :itemId="itemId" :unitId="unitId" :floorId="floorId"
                    appPermission="建设单位"
                    @submitedProblem="submitedProblem"
                    v-else-if="hasPermissionConstructor">
                </WorkbenchQualityMeasureProblemRegist>
            </f7-tab>
        </f7-tabs>
        <SheetCascader2 ref="placeCascader" 
            :options="placeTrees" 
            :value="[buildingId, unitId, floorId, houseId]"
            @change="placeChange">
        </SheetCascader2>
        <SheetCascader2 ref="checkItemCascader" 
            :options="checkItemTrees"
            :value="[parentProblemClassId, problemClassId]" 
            @change="checkItemChange">
        </SheetCascader2>
    </f7-page>
</template>

<script>
import Common from "@/utils/Common.js";
import DateUtil from "@/utils/DateUtil.js";
import $ from 'jquery';
import events from 'events';
import store from '@/store';
import keys from '@/utils/rememberKeys';
import request from '@/utils/request';
import db from '@/utils/db';
import { getUser, setUser, clearUser } from '@/utils/auth';
import { getStore, setStore, clearStore } from '@/utils/storage';
import WorkbenchQualityMeasureProblemDetail from "@/views/home/workbench/qualityMeasure/ProblemDetail.vue";
import WorkbenchQualityMeasureProblemRegist from '@/views/home/workbench/qualityMeasure/ProblemRegist.vue';
import SheetCascader from "@/views/common/SheetCascader.vue";
import SheetCascader2 from "@/views/common/SheetCascader2.vue";

export default {
    store: store,
    components: {
    	WorkbenchQualityMeasureProblemDetail,
    	WorkbenchQualityMeasureProblemRegist,
    	SheetCascader,
    	SheetCascader2
    },
    data: function() {
        return {
            placeTrees: [],
            checkItemTrees: [],
            parentProblemClassId: null,
            problemClassId: null,
            bidSectionId: null,
            buildingId: null,
            floorId: null,
            unitId: null,
        	houseId: null,
        	qualityMeasure: {
        		'施工单位': null,
        		'监理单位': null,
        		'建设单位': null
        	},
        	itemId: null
        };
    },
    methods: {
    	pageBeforeIn: function() {
            var self = this;
    		this.$f7.preloader.show();
            let sql = "\
        	    select t.*, p.repair \
        	    from tb_quality_measure_checkquality_problem t \
        	    left join tb_quality_measure_checkquality_repair p \
        	    on t.id = p.quality_measure_checkquality_problem_id \
        	    where p.child_quality_measure_checkquality_repair_id  is null \
        	    and t.item_id = '" + self.problemClassId + "' \
        	    and t.unit_id = '" + self.unitId + "' \
        	    and t.floor_id = '" + self.floorId + "' \
        	";
        	let checkItemGuideline = self.$store.state.global.checkItemGuidelineMap[self.problemClassId];
        	if(checkItemGuideline == null || checkItemGuideline.process_mode == '1') {
        		sql += "\
        		    and t.room_id = '" + self.houseId + "' \
        		";
        	}
        	Common.executeSql(sql, []).then((result) => {
        		let rs = result.rs;
        		var qualityMeasure = {
                    '施工单位': null,
                    '监理单位': null,
                    '建设单位': null
                };
           		for(var i = 0; i < rs.rows.length; i++) {
           			var row = rs.rows.item(i);
                       row = self.convertQualityMearueProblemRow(row);
                       qualityMeasure[row.app_permission] = row;
           		}
                self.qualityMeasure = qualityMeasure;
                this.$f7.preloader.hide();
        	}).catch(error => {
    			console.error(error);
    			this.$f7.preloader.hide();
    		});
            
    	},
    	submitedProblem: function(problem) {
    		var self = this;
    		this.$f7.preloader.show();
    		let sql = 
    			"select id, update_time " +
    			"from tb_quality_measure_checkquality_problem t " +
    			"where item_id = '" + self.problemClassId + "' ";
    		Common.executeSql(sql, []).then((result) => {
    			let problems = [problem];
    			let rs = result.rs;
    			let localMap = {};
                for(var i = 0; i < rs.rows.length; i++) {
                    let row = rs.rows.item(i);
                    let item = {};
                    item.id = row['id'];
                    item.update_time = row['update_time'];
                    localMap[item.id] = item;
                }
                let elements = [];
                for(var i = 0; i < problems.length; i++) {
                	let element = problems[i];
                	if(localMap[element.id] == null) {
                		elements.push(element);
                	}
                }
                let sql = 
                    "insert into tb_quality_measure_checkquality_problem ( " +
                    "id, update_time, batch_type, drawing_file, image_file, measure_points, " +
                    "problem_points, problem_values, regist_date, remark, repair_date, repair_image_file, " +
                    "repair_remark, sent_back_date, sent_back_image_file, sent_back_remark, sent_back_times, small_image_file, " +
                    "small_repair_image_file, small_sent_back_image_file, standard_min, standard_max, status, " +
                    "building_id, floor_id, room_id, item_id, " +
                    "regist_by, repair_by, unit_id, app_permission, ccs) " +
                    "values ( " +
                    "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " +
                    "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " +
                    "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ";
                let batchSql = [];
                for(var i = 0; i < elements.length; i++) {
            		var element = elements[i];
        			var values = [
        				element.id,
            			element.updateTimestamp,
            			element.batchType,
            			element.drawingFile,
            			element.imageFile,
            			element.measurePoints,
            			element.problemPoints,
            			element.problemValues,
            			element.registTimestamp,
            			element.remark,
            			element.repairTimestamp,
            			element.repairImageFile,
            			element.repairRemark,
            			element.sentBackTimestamp,
            			element.sentBackImageFile,
            			element.sentBackRemark,
            			element.sentBackTimes,
            			element.smallImageFile,
            			element.smallRepairImageFile,
            			element.smallSentBackImageFile,
            			element.standardMin,
            			element.standardMax,
            			element.status,
            			element.buildingId,
            			element.floorId,
            			element.roomId,
            			element.itemId,
            			element.registBy,
            			element.repairBy,
            			element.unitId,
            			element.appPermission,
            			element.ccs
                    ];
        			batchSql[i] = [sql, values];
                }
                return Common.sqlBatch(batchSql);
    		}).then((result) => {
    			return request({
            		url: '/api/qualityMeasureCheckQualityRepair/findByQualityMeasureProblemId',
            		method: 'GET',
            		params: {
                        qualityMeasureProblemId: problem.id
                    },
                    headers: {
    					'Content-Type': 'application/x-www-form-urlencoded'
    				}
            	});
    		}).then((data) => {
    			let sql = 
    				"select id, update_time " +
    				"from tb_quality_measure_checkquality_repair t ";
    			let promise = Common.executeSql(sql, []).then((result) => {
    				let repairs = data.list;
    				let rs = result.rs;
    				let localMap = {};
    	            for(var i = 0; i < rs.rows.length; i++) {
    	                let row = rs.rows.item(i);
    	                let item = {};
    	                item.id = row['id'];
    	                item.update_time = row['update_time'];
    	                localMap[item.id] = item;
    	            }
    	            let elements = [];
    	            for(var i = 0; i < repairs.length; i++) {
    	            	let element = repairs[i];
    	            	if(localMap[element.id] == null) {
    	            		elements.push(element);
    	            	}
    	            }
    	            let sql = 
    	                "insert into tb_quality_measure_checkquality_repair ( " +
    	                "id, update_time, has_read, reading_time, " +
    	                "quality_measure_checkquality_problem_id, child_quality_measure_checkquality_repair_id, " +
    	                "parent_quality_measure_checkquality_repair_id, repair) " +
    	                "values (?, ?, ?, ?, ?, ?, ?, ?) ";
    	            let batchSql = [];
    	            for(var i = 0; i < elements.length; i++) {
    	        		let element = elements[i];
    	    			let values = [
    	    				element.id,
    	        			element.updateTimestamp,
    	        			element.hasRead,
    	        			element.readingTime,
    	        			element.qualityMeasureCheckqualityProblemId,
    	        			element.childQualityMeasureCheckQualityRepairId,
    	        			element.parentQualityMeasureCheckQualityRepairId,
    	        			element.repair
    	                ];
    	    			batchSql[i] = [sql, values];
    	            }
    	            return Common.sqlBatch(batchSql);
    			});
    			return promise;
    		}).then((result) => {
    			let sql = "\
                    select t.*, p.repair \
                    from tb_quality_measure_checkquality_problem t \
                    left join tb_quality_measure_checkquality_repair p \
                    on t.id = p.quality_measure_checkquality_problem_id \
                    where p.child_quality_measure_checkquality_repair_id is null \
                    and t.id = '" + problem.id + "' \
                ";
    			return Common.executeSql(sql, []);
    		}).then((result) => {
    			let rs = result.rs;
    			let row = rs.rows.item(0);
                row = self.convertQualityMearueProblemRow(row);
                self.qualityMeasure[row.app_permission] = row;
                self.$emit('submitedProblem', row);
                self.$f7router.emit('submitedProblem', row);
                self.$f7.preloader.hide();
    		}).catch(error => {
    			console.error(error);
                self.$f7.preloader.hide();
    		});
    		
            /* var emitter = new events.EventEmitter();
            emitter.on('insertQualityMeasureCheckQualityProblemsByItemId', function() {
            	
            	Common.ajax({
                    url: Common.address + '/rest/api/v3/qualityMeasureCheckQualityRepair/findByQualityMeasureProblemId',
                    type: 'GET',
                    xhrFields: {
                        withCredentials: true
                    },
                    data: {
                    	qualityMeasureProblemId: problem.entityId
                    },
                    timeout: 60000,
                    success: function(result) {
                        var emitter = new events.EventEmitter();
                        emitter.once('insertQualityMeasureCheckQualityRepairs', function() {
                            window.db.transaction(function(tx) {
                                var sql = "\
                                    select t.*, p.repair \
                                    from tb_quality_measure_checkquality_problem t \
                                    left join tb_quality_measure_checkquality_repair p \
                                    on t.quality_measure_checkquality_problem_id = p.quality_measure_checkquality_problem_id \
                                    where p.child_qualityMeasureCheckQualityRepair_id is null \
                                    and t.quality_measure_checkquality_problem_id = '" + problem.entityId + "' \
                                ";
                                tx.executeSql(sql, [], function(tx, rs) {
                                    var row = rs.rows.item(0);
                                    row = self.convertQualityMearueProblemRow(row);
                                    self.qualityMeasure[row.app_permission] = row;
                                    self.$emit('submitedProblem', row);
                                    self.$f7router.emit('submitedProblem', row);
                                    self.$f7.preloader.hide();
                                });
                            }, function(error) {
                                console.error(error);
                                self.$f7.preloader.hide();
                            });
                        });
                        window.insertQualityMeasureCheckQualityRepairs(result.elements, emitter);
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                    	self.$f7.preloader.hide();
                    }
            	});
            });
            window.insertQualityMeasureCheckQualityProblemsByItemId(
                [problem], this.problemClassId, emitter); */
    	},
    	modifiedProblem: function(row) {
    		var self = this;
    		var row = this.convertQualityMearueProblemRow(row);
    		self.qualityMeasure[row.app_permission] = row;
            self.$emit('submitedProblem', row);
            self.$f7router.emit('submitedProblem', row);
    	},
    	convertQualityMearueProblemRow: function(row) {
    		row.drawing_file = Common.strToJson(row.drawing_file);
            row.image_file = Common.strToJson(row.image_file);
            row.problem_values = Common.strToJson(row.problem_values);
            row.repair_image_file = Common.strToJson(row.repair_image_file);
            row.sent_back_image_file = Common.strToJson(row.sent_back_image_file);
            row.small_image_file = Common.strToJson(row.small_image_file);
            row.small_repair_image_file = Common.strToJson(row.small_repair_image_file);
            row.small_sent_back_image_file = Common.strToJson(row.small_sent_back_image_file);
            row.regist_date = row.regist_date && new Date(row.regist_date);
            row.repair_date = row.repair_date && new Date(row.repair_date);
            row.sent_back_date = row.sent_back_date && new Date(row.sent_back_date);
            row.ccs = Common.strToJson(row.ccs);
            row.repair = row.repair;
            return row;
    	},
        placeCascaderOpen: function() {
            this.$refs.placeCascader.open();
        },
        placeChange: function(values) {
            this.buildingId = values[0];
            this.unitId = values[1];
            this.floorId = values[2];
            this.houseId = values[3];
        },
        checkItemCascaderOpen: function() {
            this.$refs.checkItemCascader.open();
        },
        checkItemChange: function(values) {
            this.parentProblemClassId = values[0];
            this.problemClassId = values[1];
        },
        updateProblem: function() {
        	this.reloadQualityMeasure();
        },
        reloadQualityMeasure: function() {
            var self = this;
            let sql = "\
                select t.*, p.repair \
                from tb_quality_measure_checkquality_problem t \
                left join tb_quality_measure_checkquality_repair p \
                on t.id = p.quality_measure_checkquality_problem_id \
                where p.child_quality_measure_checkquality_repair_id is null \
                and t.item_id = '" + self.problemClassId + "' \
                and t.unit_id = '" + self.unitId + "' \
                and t.floor_id = '" + self.floorId + "' \
            ";
            let checkItemGuideline = self.$store.state.global.checkItemGuidelineMap[self.problemClassId];
            if(checkItemGuideline == null || checkItemGuideline.process_mode == '1') {
                sql += "\
                    and t.room_id = '" + self.houseId + "' \
                ";
            }
            Common.executeSql(sql, []).then((result) => {
            	let rs = result.rs;
            	var qualityMeasure = {
                    '施工单位': null,
                    '监理单位': null,
                    '建设单位': null
                };
                for(var i = 0; i < rs.rows.length; i++) {
                    var row = rs.rows.item(i);
                    row = self.convertQualityMearueProblemRow(row);
                    qualityMeasure[row.app_permission] = row;
                }
                self.qualityMeasure = qualityMeasure;
            }).catch(error => {
    			console.error(error);
    		});
            
        },
        downloadQualityMeasureCheckProblems: function() {
            var self = this;
            self.$f7.preloader.show();
           	let sql = "delete from tb_quality_measure_checkquality_problem where floor_id = ? and item_id = ?";
           	Common.executeSql(sql, [self.floorId, self.problemClassId]).then(() => {
               	return request({
               		url: '/rest/api/v3/qualityMeasureCheckQualityProblem/findByFloorIdAndItemId',
                       method: 'get',
                       params: {
                           floorId: self.floorId,
                           itemId: self.problemClassId
                       }
                   });
       		}).then((data) => {
       			var elements = data.list;
       			if(elements == null){
       				elements = [];
       			}
       			db.insert('tb_quality_measure_checkquality_problem', elements);
       			self.$f7.preloader.hide();
       			self.reloadQualityMeasure();
       		}).catch(error => {
       			console.error(error);
       			self.$f7.preloader.hide();
       			self.reloadQualityMeasure();
       		});
            
        },
        buildPlaceTrees: function() {
        	var checkItemGuideline = this.$store.state.global.checkItemGuidelineMap[this.problemClassId];
        	var projectId = getStore(keys.projectIdKey);
        	var bidSectionMap = {};
        	var buildingMap = {};
            var unitMap = {};
            var floorMap = {};
            var houseMap = {};
            var placeTrees = [];
            let sql = "select * from tb_unit where building_id in (select id from tb_building where project_id = ? )";
            Common.executeSql(sql, [projectId]).then((result) => {
            	let rs = result.rs;
        		for(let i = 0; i < rs.rows.length; i++) {
        			let unit = rs.rows.item(i);
        			var unitTree = {
                            value: unit.id,
                            displayValue: unit.unit_name + '单元',
                            children: []
                        };
                        unitMap[unitTree.value] = unitTree;
                        var buildingTree = buildingMap[unit.building_id];
                        if(buildingTree == null) {
                            var building = this.$store.state.global.buildingMap[unit.building_id];
                            buildingTree = {
                                value: building.id,
                                displayValue: building.building_name,
                                children: []
                            };
                            buildingMap[buildingTree.value] = buildingTree;
                            placeTrees.push(buildingTree);
                        }
                        buildingTree.children.push(unitTree);
        		}
        		let sql = "select * from tb_house where floor_id in (select id from tb_floor where building_id in (select id from tb_building where project_id = ? ))";
        		return Common.executeSql(sql, [projectId]);
            }).then((result) => {
            	let rs = result.rs;
            	for(var i = 0; i < rs.rows.length; i++) {
	        		var house = rs.rows.item(i);
	        		var houseTree = {
                		value: house.id,
                		displayValue: house.house_name,
                		children: []
                	}
                	houseMap[houseTree.value] = houseTree;
                	var floorTree = floorMap[house.unit_id + '_' + house.floor_id];
                	if(floorTree == null) {
                		var floor = this.$store.state.global.floorMap[house.floor_id];
                		floorTree = {
                			value: floor.id,
                			displayValue: floor.floor_name,
                			children: []
                		}
                		floorMap[house.unit_id + '_' + house.floor_id] = floorTree;
                        var unitTree = unitMap[house.unit_id];
                		unitTree.children.push(floorTree);
                	}
                	if(checkItemGuideline == null || checkItemGuideline.process_mode == '1') {
                        floorTree.children.push(houseTree);
                	}
	        	}
	        	for(var key in unitMap) {
	            	var unitTree = unitMap[key];
	            	unitTree.children.sort(function(f1, f2) {
	            		var f1Num = parseInt(f1.displayValue);
	            		var f2Num = parseInt(f2.displayValue);
	            		if(isNaN(f1Num)) {
	            			return 1;
	            		}
	            		if(isNaN(f2Num)) {
	            			return -1;
	            		}
	            		if(f1Num < f2Num) {
	            			return -1;
	            		}
	            		if(f1Num == f2Num) {
	            			return 0;
	            		}
	            		if(f1Num > f2Num) {
	            			return 1;
	            		}
	            	});
	            }
	            for(var key in floorMap) {
	            	var floorTree = floorMap[key];
	            	floorTree.children.sort(function(h1, h2) {
	            		var h1Num = parseInt(h1.displayValue);
	            		var h2Num = parseInt(h2.displayValue);
	            		if(isNaN(h1Num)){
	            			return 1;
	            		}
	            		if(isNaN(h2Num)){
	            			return -1;
	            		}
	            		if(h1Num < h2Num) {
	            			return -1;
	            		}
	            		if(h1Num == h2Num) {
	            			return 0;
	            		}
	            		if(h1Num > h2Num) {
	            			return 1;
	            		}
	            	});
	            }
	            this.placeTrees = placeTrees;
            	
            }).catch(error => {
    			console.error(error);
    		});
            
        }
    },
    computed: {
        hasPermissionContractor: function() {
            var userId = getUser().userId;
            var user = this.$store.state.global.userMap[userId];
            if(user.app_permission == '施工单位' || user.app_permission == '监理单位' || user.app_permission == '建设单位') {
                return true;
            } else {
                return false;
            }
        },
        hasPermissionSupervisor: function() {
            var userId = getUser().userId;
            var user = this.$store.state.global.userMap[userId];
            if(user.app_permission == '监理单位' || user.app_permission == '建设单位') {
                return true;
            } else {
                return false;
            }
        },
        hasPermissionConstructor: function() {
            var userId = getUser().userId;
            var user = this.$store.state.global.userMap[userId];
            if(user.app_permission == '建设单位') {
                return true;
            } else {
                return false;
            }
        }
    },
    watch: {
        
    },
    created: function() {
        this.bidSectionId = this.$f7route.query.bidSectionId;
        this.buildingId = this.$f7route.query.buildingId;
        this.floorId = this.$f7route.query.floorId;
        this.unitId = this.$f7route.query.unitId;
        this.houseId = this.$f7route.query.houseId;
        this.problemClassId = this.$f7route.query.itemId;
        this.parentProblemClassId = 
            this.$store.state.global.problemClassMap[this.problemClassId].parent_problem_class_id;
    	this.itemId = this.problemClassId;
        
        var checkItemGuideline = this.$store.state.global.checkItemGuidelineMap[this.problemClassId];
        
        this.buildPlaceTrees();
        
        var problemClasses = [];
        var problemClassIds = this.$store.state.global.bidSectionCheckItemRel.bidSectionMap[this.bidSectionId];
        for(var itemId in problemClassIds){
        	var problemClass = this.$store.state.global.problemClassMap[
        		this.$store.state.global.bidSectionCheckItemRel[problemClassIds[itemId]].check_item_id
        	];
            if(problemClass.type == '41') {
            	if(!problemClasses.includes(problemClass)){
            		problemClasses.push(problemClass);
            	}
            }
        }
        problemClasses = problemClasses.sort(function(pc1, pc2) {
            if(pc1.level < pc2.level) {
                return -1;
            } else if(pc1.level == pc2.level) {
                return 0;
            } else {
                return 1;
            }
        });
        var checkItemTrees = [];
        var checkItemTreeMap = {};
        for(var i = 0; i < problemClasses.length; i++) {
            var problemClass = problemClasses[i];
            var checkItemTree = {
                value: problemClass.id,
                displayValue: problemClass.problem_class_name,
                children: []
            };
            checkItemTreeMap[checkItemTree.value] = checkItemTree;
            if(problemClass.level == 2) {
                checkItemTrees.push(checkItemTree);
            } else {
                var parentCheckItemTree = checkItemTreeMap[problemClass.parent_problem_class_id];
                parentCheckItemTree.children.push(checkItemTree);
            }
        }
        if(checkItemTreeMap[this.problemClassId] == null) {
            this.parentProblemClassId = checkItemTrees[0].value;
            this.problemClassId = checkItemTrees[0].children[0].value;
        } else {
            this.parentProblemClassId = 
                this.$store.state.global.problemClassMap[this.problemClassId].parent_problem_class_id;
        }
        this.checkItemTrees = checkItemTrees;
    },
    mounted: function() {
    	var self = this;
    	this.$watch('houseId', function(newVal, oldVal) {
    		this.downloadQualityMeasureCheckProblems();
    	});
    	this.$watch('problemClassId', function(newVal, oldVal) {
    		var self = this;
    		var oldCheckItemGuideline = this.$store.state.global.checkItemGuidelineMap[oldVal];
    		var newCheckItemGuideline = this.$store.state.global.checkItemGuidelineMap[newVal];
    		if(oldCheckItemGuideline.process_mode != '1' && newCheckItemGuideline.process_mode == '1'){
    			var floor = self.$store.state.global.floorMap[this.floorId];
    			var houses = floor.houses.concat();
    			houses = houses.filter(function(house) {
    				return house.unit_id == self.unitId;
    			}).sort(function(h1,h2) {
    				var h1Num = parseInt(h1.house_name);
    				var h2Num = parseInt(h2.house_name);
    				if(isNaN(h1Num)){
            			return 1;
            		}
            		if(isNaN(h2Num)){
            			return -1;
            		}
            		if(h1Num < h2Num) {
            			return -1;
            		}
            		if(h1Num == h2Num) {
            			return 0;
            		}
            		if(h1Num > h2Num) {
            			return 1;
            		}
    			});
    			this.houseId = houses[0].id;
    			self.buildPlaceTrees();
    		} else if(oldCheckItemGuideline.process_mode == '1' && newCheckItemGuideline.process_mode != '1'){
    			self.houseId = null;
    			self.buildPlaceTrees();
    		} else {
    			self.downloadQualityMeasureCheckProblems();
    		}
    		this.itemId = this.problemClassId;
    	});
    	this.$watch('floorId', function(newVal, oldVal) {
    		var checkItemGuideline = this.$store.state.global.checkItemGuidelineMap[this.problemClassId];
    		if(checkItemGuideline) {
    			if(checkItemGuideline.process_mode != '1') {
    				this.downloadQualityMeasureCheckProblems();
    			}
    		}
    	});
    }
}
</script>

<style scoped>

</style>